$NG.AllReady(function (page, { useDataIndexChange, useUpdateRow,useValuesChange , useUpdateRows }) {
    // 编辑页面逻辑
    const mstform = $NG.getCmpApi("p_form_employ_projbal");
    const grid1 = $NG.getCmpApi("p_form_employ_projbal_d");
    const grid2 = $NG.getCmpApi("p_form_employ_projbal_d1");
    // 缓存存储过滤的工资表内容
    const salaryTable = {}
    // 缓存其他合同初始累计
    let _cntSalary = {}
    // 存储并设置表体对象
    const cntSalary = {
        _cnt_amt:0,
        _cnt_sq_amt:0,
        _cnt_kp_amt:0,
        set cnt_amt(value){
            this._cnt_amt = Number(value)
            setCntAmt(this._cnt_amt,this._cnt_sq_amt,this._cnt_kp_amt)
        },
        set cnt_sq_amt(value){
            this._cnt_sq_amt = Number(value)
            setCntAmt(this._cnt_amt,this._cnt_sq_amt,this._cnt_kp_amt)
        },
        set cnt_kp_amt(value){
            this._cnt_kp_amt = Number(value)
            setCntAmt(this._cnt_amt,this._cnt_sq_amt,this._cnt_kp_amt)
        },
    }
    $NG.execServer("getInfo", {}, function(res){
        console.log('测试', res);
    })
    cntMFilter()
    // 监听表格行变化
    useUpdateRow(({args})=>{
        initSalary(args)
    },"p_form_employ_projbal_d")
    // 监听支付比例
    useValuesChange(({args})=>{
        console.log(`监听支付比例`, args);
        const dArr = grid1.getRows()
        dArr.forEach(item =>{
            if(!item.u_zfbl) {
                item.u_zfbl = args[0].u_zf_bfb
            }
        })
        grid1.refreshView()
    },"p_form_employ_projbal.u_zf_bfb")
    // /10.表体数据变化（增行、删行、引入）时，汇总计算至表头
    useUpdateRows(({ args }) => {
        console.log(`表体监听`, args);
        args[0].forEach((item, index) =>{
            if(!item.u_zfbl){
                item.u_zfbl = mstform.getItem("u_zf_bfb").getValue()
            }
            if(args[0].length-1 == index){grid1.refreshView()}
        })
        sum()
        var sumAmt = 0;
        const rows = args[0];
        rows.forEach((items) => {
            if (items.u_approve_amt) {
                sumAmt += parseFloat(items.u_approve_amt);
            }
            //汇总赋值
            $NG.updateState((updater) => {
                updater.data.p_form_employ_projbal.setProps({
                    u_apply_amt: sumAmt,

                });
            });
        });
    }, "p_form_employ_projbal_d");
//表体发票金额合计
    useUpdateRows(({ args }) => {
        
        sum()
        var sumAmt = 0;
        const rows = args[0];
        rows.forEach((items) => {
            if (items.u_invo_amt) {
                sumAmt += parseFloat(items.u_invo_amt);
            }
            //汇总赋值
            $NG.updateState((updater) => {
                updater.data.p_form_employ_projbal.setProps({
                    u_bcfpje: sumAmt,

                });
            });
        });
    }, "p_form_employ_projbal_d1");
    // 监听项目发生变化
    useValuesChange(({args})=>{
        getProjectInfo()
        cntMFilter()
        $NG.updateState((updater) => {
            updater.data.p_form_employ_projbal.setProps({
                u_cnt:{
                    label:"",
                    value:""
                },
                u_cnt_no:""

            });
        });
    }, "p_form_employ_projbal.phid_pc")

    useValuesChange(({args})=>{
        console.log(`监听合同`, args);
        grid1.clearRows()
        getCntInfo()
        getSalaryTable()
        cntDFilter()
        allSalary()
    }, "p_form_employ_projbal.u_cnt")

    function sum (){
        const _row1 = grid1.getRows()
        const _row2 = grid2.getRows()
        let _count1 = 0
        let _count1_1 = 0
        let _count2 = 0;
        let _count2_1 = 0;
        _row1.forEach(element => {
            _count1+=Number(element.u_apply_amt)
            _count1_1 += Number(element.u_approve_amt)
        });
        _row2.forEach(element=>{
            _count2 += Number(element.u_invo_amt)
            _count2_1 += Number(element.u_invo_tax)
        })
        $NG.updateState((updater)=>{
            console.log(_cntSalary, '测试');
            cntSalary.cnt_amt = ((_count1_1||0) + _cntSalary.cnt_amt)
            cntSalary.cnt_sq_amt = ((_count1||0) + _cntSalary.cnt_sq_amt)
            cntSalary.cnt_kp_amt = ((_count2||0) + _cntSalary.cnt_kp_amt)
            updater.data.p_form_employ_projbal.setProps({
                u_bc_apply_amt: _count1,
                u_approve_amt: _count1_1,
                u_bcfpje: _count2,
                u_yksje: _count2_1
            })
        })
    }

    //获取项目信息
    function getProjectInfo(){
        console.log(mstform.getItem("phid_pc").getValue());
        $NG.execServer("getPtInfoByPhid", {phid:mstform.getItem("phid_pc").getValue()}, (res)=>{
            const _data = JSON.parse(res.data)[0].extendObjects
            console.log(`获取项目信息`, _data);
            $NG.updateState((updater)=>{
                updater.data.p_form_employ_projbal.setProps({
                    u_agreed_sts_dt: _data.start_date, //计划完工日期
                    u_agreed_pcl_dt: _data.end_date, //计划竣工日期
                    u_sqgw: {
                        //售前顾问
                        value: _data.user_sqgw_phid,
                        label: _data.user_sqgw_name,
                    },
                    u_division: {
                        //事业部or组织or分公司
                        value: _data.org_phid,
                        label: _data.org_name,
                    },
                    // 分公司
                    u_fgs:{
                        value: _data.org_phid,
                        label: _data.org_name,
                    },
                    u_regional_center: {
                        //区域中心
                        value: _data.regional_center_phid,
                        label: _data.regional_center_name,
                    },
                    u_product_line: {
                        //产品线
                        value: _data.midwife_phid,
                        label: _data.midwife_name,
                    },
                    u_dept: {
                        //部门
                        value: _data.dept_phid,
                        label: _data.dept_name,
                    },
                    u_pc_type: {//项目类型
                        value: _data.type_phid,
                        label: _data.type_name,
                    },
                    u_pc_no:_data.pc_no
                })
            })
        })
    }
    // 过滤函数
    function cntMFilter() {
		if (!mstform.getItem("phid_pc").getValue()) {
			return;
		}
        console.log(`开始过滤`);
		$NG.updateUI((updater, state) => {
			updater.form.p_form_employ_projbal.u_cnt.setProps({
				onBeforeOpen: async () => {
					var phid_pc = $NG
						.getCmpApi("p_form_employ_projbal")
						.getItem("phid_pc")
						.getValue();
					if (!phid_pc) {
						$NG.alert("请先选择项目");
						return false;
					} else {
						return true;
					}
				},
				...(!!$NG
					.getCmpApi("p_form_employ_projbal")
					.getItem("phid_pc")
					.getValue() && {
					clientSqlFilter: {
						xm_no: $NG
							.getCmpApi("p_form_employ_projbal")
							.getItem("phid_pc")
							.getValue(),
					},
				}),
			});
		});
	}

    // 获取合同信息
    function getCntInfo(){
        $NG.execServer(
            "GetWbhtInfo",
            { phid: mstform.getItem("u_cnt").getValue() },
            function (res) {
                console.log(mstform.getItem("u_cnt").getValue(),res);
                if(res.count ==0 ){return}
                const datas = JSON.parse(res.data)[0].extendObjects;
                console.log(`合同：`,datas);
                //帮助字段赋值
                $NG.updateState((updater) => {
                    updater.data.p_form_employ_projbal.setProps({
                        u_cnt_no:datas.bill_no,
                        u_cnt_amt:datas.amt
                    });
                });
            }
        );
    }

    // 获取工资表
    function getSalaryTable(){
        $NG.execServer("getSalaryTableInfo", {phid:mstform.getItem("u_cnt").getValue()}, function (res){
            console.log(`工资表响应数据`, res);
            if(res.count == 0){return}
            const _data = JSON.parse(res.data)
            console.log(`获取工资表`, _data);
            _data.forEach((item)=>{
                const _d = item.extendObjects
                salaryTable[_d.phid] = {..._d}
            })
        })
    }

    function cntDFilter() {
    const phid_pcc = $NG.getCmpApi('p_form_employ_projbal').getItem('u_cnt').getValue();
    if(!phid_pcc){
        return 
    }
    $NG.updateUI(updater => {
        console.log(`附表过滤`, updater);
        updater.editGrid.p_form_employ_projbal_d.u_yg_billno.setProps((p) => {
            console.log(`正在过滤`);
            return {
            ...p, editor: {
                ...p.editor,
                clientSqlFilter: { u_cnt_name: $NG.getCmpApi('p_form_employ_projbal').getItem('u_cnt').getValue() },
            }
            };
        })
    });
}

// 监听d表体的时候赋值其他字段
    function initSalary(arg){
        const _data = salaryTable[arg[0].u_yg_billno]
        if(!_data) {
            $NG.alert("找不到单据或单据选择不正确/空！")
        }
        console.log(_data, salaryTable[arg[0].u_yg_billno],salaryTable);
        arg[0].u_apply_amt_vat = _data.total_amt
        arg[0].u_apply_amt = _data.total_amt
        if(!arg[0].u_approve_amt&&arg[0]!==0){
            arg[0].u_approve_amt = _data.total_amt
        }
        grid1.refreshView()
    }
    // 获取合同累计金额
    function allSalary(){
        $NG.execServer("getAllYfdInfo",{},function(res){
            const _data = JSON.parse(res.data)[0].extendObjects
            console.log(_data);
            _cntSalary = {..._data}
            Object.keys(_data).forEach(item=>{
                cntSalary[item] = _data[item]
            })
        })
    }
    // 设置主表合同累计金额字段
    function setCntAmt(_c1,_c2,_c3){
        console.log(_c1,_c2,_c3);
        $NG.updateState((updater)=>{
            updater.data.p_form_employ_projbal.setProps({
                // 累计付款
                u_total_payamt:_c1,
                // 累计开票
                u_htkp_amt:_c2,
                // 累计申请
                u_ht_apply_amt:_c3,
            })
        })
    }
//添加按钮

const gridToolbar = $NG.getCmpApi("toolbar_p_form_employ_projbal_d1")
$NG.getCmpApi('toolbar_p_form_employ_projbal_d1').insert({
    id: "myadd",
    text: "发票引用",
    iconCls: "icon-New"
});
});

